package com.pdx.shiro;

import com.pdx.config.RedisService;
import com.pdx.constant.Constant;
import com.pdx.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

/**
 * @author PDX
 * @website https://blog.csdn.net/Gaowumao
 * @Date 2022-04-30 22:29
 * @Description 自定义Realm类
 */
@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CustomUsernamePasswordToken;
    }
    /**
     * 授权机制
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String accessToken = (String) principals.getPrimaryPrincipal();
        Claims claims = JwtTokenUtil.getClaimsFromToken(accessToken);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (claims.get(Constant.ROLES_INFOS_KEY) != null){
            info.addRoles((Collection<String>) claims.get(Constant.ROLES_INFOS_KEY));
        }
        if (claims.get(Constant.PERMISSIONS_INFOS_KEY)!=null){
            info.addStringPermissions((Collection<String>) claims.get(Constant.PERMISSIONS_INFOS_KEY));
        }
        return info;
    }
    /**
     * 认证机制
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        CustomUsernamePasswordToken usernamePasswordToken = (CustomUsernamePasswordToken) token;
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(usernamePasswordToken.getPrincipal(), usernamePasswordToken.getCredentials(), getName());
        return info;
    }
}
